<?php

/*------------------------------------------------
*
*   Explay Engine Content Management System.
*   Copyright © 2008 Golovdinov Alexander.
*
*-------------------------------------------------
*
*   Official site: wwww.alex-home.spb.ru/explay.html
*   Contact e-mail: golovdinov@gmail.com
*
*   GNU General Public License original source:
*   http://www.gnu.org/licenses/gpl-3.0.html
*
------------------------------------------------*/


header ("Cache-control: no-cache");
header ("Content-Type: text/html; charset=utf-8");

define ('EXPLAY', 1);


include $_SERVER['DOCUMENT_ROOT'].'/engine/functions.php';       // Основное API
include $_SERVER['DOCUMENT_ROOT'].'/engine/settings.php';        // Настроки сайта
include $_SERVER['DOCUMENT_ROOT'].'/engine/mysql.class.php';     // БД
include $_SERVER['DOCUMENT_ROOT'].'/engine/user.class.php';      // Объект пользователя
include $_SERVER['DOCUMENT_ROOT'].'/engine/connect.php';         // Подключение к БД и начальная инициализация
include $_SERVER['DOCUMENT_ROOT'].'/engine/templates.class.php';

$theme = $SITE['site_theme'];

// Make template class
Templater::$path = $_SERVER['DOCUMENT_ROOT']."/themes/$theme/";

if (is_registered())
	Templater::$user = User::$properties['user_group'];
else
	Templater::$user = 'user';

if (isset($_POST['enter'])) {
	
	if (isset($_POST['openid_login']) && isset($_POST['openid_server']))
		openid_redicret ();
	
	elseif ($_GET['openid_mode'] == 'id_res')
		get_params ();
	
	else 		
		User::login ();
}
elseif (isset($_GET['logout']))
	User::logout ();

else	
	User::mess ('/', 'Вход в систему');



function print_big_authorization ($message, $url) {
	global $template;
	$template->set_var ('{URL}', $url);
	$template->set_var ('{MESSAGE}', $message);
	print $template->display ('authorization.tpl');
}




/*
 *
 * - Зачем нужены следующие функции и библиотека OpenID?
 * - Без понятия. Они Вам мешают?
 * - Н-н-нет... а все-таки, есть причина по которой они здесь?
 * - Есть. Однажды, они сюда пришли и не хотят уходить. Попробуйте их убрать отсюда.
 *
 */



function openid_redicret () {
	
	
	global $url_, $SITE;
	
	include 'engine/openid.class.php';
	
	
	$openid = new SimpleOpenID;
	
	$id = trim ($_POST['openid_login']) . '.' . trim ($_POST['openid_server']);
	$id = str_replace ('http://', '', $id);
	$id = "http://$id";
	if (substr($id, strlen($id)-2, strlen($id)-1) != '/') $id = $id.'/';
	
	$openid->SetIdentity($id);
	$openid->SetTrustRoot('http://'. $_SERVER['HTTP_HOST'] .'/');
	$openid->SetRequiredFields(array('fullname'));
	//$openid->SetOptionalFields(array('dob','gender','postcode','country','language'));
	
	if ($openid->GetOpenIDServer()){
		
		(isset ($_POST['openid_remember'])) ? $_SESSION['rem_time'] = time() + ($SITE['cookie_live'] * 86400) : $_SESSION['rem_time'] = 0;
		$_SESSION['save_location'] = $url_;
		
		$openid->SetApprovedURL('http://'. $_SERVER['HTTP_HOST'] .'/login.html');
		$openid->Redirect();
	}
	else print_big_authorization ("Невозможно найти OpenID сервер! $id", $url_);



}



function get_params () {
	
	global $time;

	include 'engine/openid.class.php';
	
	
	$openid = new SimpleOpenID;
	
	
	$openid->SetIdentity($_GET['openid_identity']);
	$openid_validation_result = $openid->ValidateWithServer();
	
	if ($openid_validation_result == true) { 
		
		
		$fullname = strip_tags ($_GET['openid_sreg_fullname']);
		
		if ($fullname == '') {
			print_big_authorization ('Ошибка OpenID сервера!', $_SESSION['save_location']);
			exit;
		}
		
		setcookie ('openid',      urlencode ($_GET['openid_identity'].'=='.$fullname),       $_SESSION['rem_time'], '/', $_SERVER['HTTP_HOST'], 0);
				
		big_message ("Добро пожаловать, $fullname!", $_SESSION['save_location']);
		
		
				
	}
	else print_big_authorization ('Ошибка OpenID сервера!', $_SESSION['save_location']);

}